package org.yunai.yfserver.plugin.mina.session;

import org.apache.mina.core.session.IoSession;
import org.yunai.yfserver.message.IMessage;
import org.yunai.yfserver.session.ISession;

import java.net.InetSocketAddress;

/**
 * mina会话，封装了mina原生的{@link org.apache.mina.core.session.IoSession}
 * User: yunai
 * Date: 13-3-26
 * Time: 上午12:29
 */
public abstract class AbstractMinaSession implements ISession {

    /**
     * Mina 会话<br />
     * 该值有可能为空
     */
    private volatile IoSession session;

    public AbstractMinaSession(IoSession session) {
//        Assert.notNull(session, "session can't be null.");
        this.session = session;
    }

    public long getId() {
        return session.getId();
    }

    @Override
    public boolean isConnected() {
        return session != null && session.isConnected();
    }

    @Override
    public void write(IMessage msg) {
        if (session != null) {
            session.write(msg);
        }
    }

    @Override
    public void close() {
        if (session != null) {
            session.close(false);
        }
    }

    /**
     * @return IP
     */
    public String getIp() {
        return ((InetSocketAddress) session.getRemoteAddress()).getAddress().getHostAddress();
    }

    @Override
    public boolean closeOnException() {
        return true;
    }
}
